
<template>
  <view class="page">
    <!-- 顶部搜索区 -->
    <view class="search-container">
      <view class="search-box" @tap="goToSearch">
        <uni-icons class="search-icon" type="search" size="20" color="#666666"></uni-icons>
        <text class="search-placeholder">搜索商品</text>
      </view>
      <view class="header-icons">
        <view class="ai-service-icon" @tap="goToAIService">
          <text class="icon-text">💬</text>
        </view>
        <view class="message-icon">
          <text class="icon-text">🔔</text>
        </view>
        <view class="cart-icon" @tap="goToCart">
          <text class="icon-text">🛒</text>
        </view>
      </view>
    </view>

    <!-- 内容滚动区 -->
    <scroll-view class="content" scroll-y>
      <!-- 轮播图 -->
      <swiper class="banner" circular autoplay interval="3000" duration="500" indicator-dots indicator-color="rgba(255, 255, 255, 0.6)" indicator-active-color="#ffffff">
        <swiper-item>
          <image class="banner-image" src="https://ai-public.mastergo.com/ai/img_res/88245d01f5ee3821c8273d88a8449cbf.jpg" mode="aspectFill"></image>
        </swiper-item>
        <swiper-item>
          <image class="banner-image" src="https://ai-public.mastergo.com/ai/img_res/bb123e2c1a4885cf50113d9b70b15c70.jpg" mode="aspectFill"></image>
        </swiper-item>
      </swiper>

      <!-- 功能导航区 -->
      <view class="nav-grid">
        <view v-for="(item, index) in navItems" :key="index" class="nav-item">
          <image class="nav-icon" :src="item.icon" mode="aspectFill"></image>
          <text class="nav-text">{{ item.text }}</text>
        </view>
      </view>

      <!-- 商品推荐区 -->
      <view class="product-section">
        <view class="section-header">
          <text class="section-title">百亿补贴</text>
          <view class="more-link">
            <text class="more-text">更多</text>
            <uni-icons type="right" size="14" color="#999999"></uni-icons>
          </view>
        </view>
        <view class="product-grid">
          <view v-for="(product, index) in products" :key="index" class="product-card" @tap="goToProductDetail(product.id)">
            <image class="product-image" :src="product.image" mode="aspectFill"></image>
            <view class="product-info">
              <view class="product-tag">{{ product.tag }}</view>
              <text class="product-title">{{ product.title }}</text>
              <view class="product-price-box">
                <text class="price-symbol">¥</text>
                <text class="product-price">{{ product.price }}</text>
                <text class="original-price">¥{{ product.originalPrice }}</text>
              </view>
              <text class="sales-count">已售{{ product.sales }}件</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { productApi, apiUtils } from '@/utils/api.js'

export default {
  data() {
    return {
      navItems: [
        {
          text: '天猫超市',
          icon: 'https://ai-public.mastergo.com/ai/img_res/7cf50a98ba7433c2fa2a119021816c7f.jpg'
        },
        {
          text: '淘鲜达',
          icon: 'https://ai-public.mastergo.com/ai/img_res/cdae2fcffef05fba934af621c683ca71.jpg'
        },
        {
          text: '天猫国际',
          icon: 'https://ai-public.mastergo.com/ai/img_res/9706cdca23b1c5faed845f2daa556372.jpg'
        },
        {
          text: '聚划算',
          icon: 'https://ai-public.mastergo.com/ai/img_res/4335e189a7cacf972e75f6c3d50e773c.jpg'
        },
        {
          text: '天猫美食',
          icon: 'https://ai-public.mastergo.com/ai/img_res/bb22a8ad966c34ddbdea3eb9315c0997.jpg'
        },
        {
          text: '充值中心',
          icon: 'https://ai-public.mastergo.com/ai/img_res/dafaea18532af57b7bfc8ab4d032ca35.jpg'
        },
        {
          text: '飞猪旅行',
          icon: 'https://ai-public.mastergo.com/ai/img_res/4a695d13869c1f0b0a60f8498cd06910.jpg'
        },
        {
          text: '领津贴',
          icon: 'https://ai-public.mastergo.com/ai/img_res/f8db4587329bd79ea8a9b53b50018d72.jpg'
        },
        {
          text: '拍卖',
          icon: 'https://ai-public.mastergo.com/ai/img_res/d6fdccf38e94b6f41fdd00b2386551f0.jpg'
        },
        {
          text: '分类',
          icon: 'https://ai-public.mastergo.com/ai/img_res/2c57ccc715e1bfee0835c7c389951c8a.jpg'
        }
      ],
      products: [],
      loading: false,
      page: 0,
      hasMore: true
    }
  },
  
  onLoad() {
    // 页面加载时获取商品数据
    this.loadProducts()
  },
  
  onReachBottom() {
    // 触底加载更多
    if (this.hasMore && !this.loading) {
      this.loadMoreProducts()
    }
  },
  
  onPullDownRefresh() {
    // 下拉刷新
    this.refreshProducts()
  },
  
  methods: {
    /**
     * 加载商品数据
     */
    async loadProducts() {
      try {
        this.loading = true
        const result = await productApi.getRecommendProducts({
          page: 0,
          size: 10
        })
        
        // 处理商品数据
        this.products = this.processProductData(result.content || [])
        this.page = 0
        this.hasMore = !result.last
        
      } catch (error) {
        console.error('加载商品数据失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 加载更多商品
     */
    async loadMoreProducts() {
      try {
        this.loading = true
        const nextPage = this.page + 1
        
        const result = await productApi.getRecommendProducts({
          page: nextPage,
          size: 10
        })
        
        // 追加商品数据
        const newProducts = this.processProductData(result.content || [])
        this.products = [...this.products, ...newProducts]
        this.page = nextPage
        this.hasMore = !result.last
        
      } catch (error) {
        console.error('加载更多商品失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 刷新商品数据
     */
    async refreshProducts() {
      try {
        const result = await productApi.getRecommendProducts({
          page: 0,
          size: 10
        })
        
        this.products = this.processProductData(result.content || [])
        this.page = 0
        this.hasMore = !result.last
        
        uni.showToast({
          title: '刷新成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('刷新商品数据失败:', error)
        uni.showToast({
          title: '刷新失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.stopPullDownRefresh()
      }
    },
    
    /**
     * 处理商品数据格式
     * @param {Array} products 原始商品数据
     * @returns {Array} 处理后的商品数据
     */
    processProductData(products) {
      return products.map(product => {
        return {
          id: product.id,
          image: apiUtils.processImageUrl(product.imageList?.[0]),
          tag: this.getProductTag(product),
          title: product.title,
          price: apiUtils.formatPrice(product.price),
          originalPrice: product.originalPrice ? apiUtils.formatPrice(product.originalPrice) : null,
          sales: apiUtils.formatSales(product.sales || 0)
        }
      })
    },
    
    /**
     * 获取商品标签
     * @param {Object} product 商品数据
     * @returns {string} 商品标签
     */
    getProductTag(product) {
      // 根据商品信息生成标签
      if (product.originalPrice && product.price < product.originalPrice) {
        const discount = Math.round((product.price / product.originalPrice) * 10)
        return `${discount}折特价`
      }
      if (product.sales > 10000) {
        return '热销爆款'
      }
      return '限时特价'
    },
    
    // 跳转到搜索页
    goToSearch() {
      uni.navigateTo({
        url: '/pages/search/search'
      })
    },
    
    // 跳转到购物车
    goToCart() {
      uni.navigateTo({
        url: '/pages/cart/cart'
      })
    },
    
    // 跳转到AI客服
    goToAIService() {
      uni.navigateTo({
        url: '/pages/aiservice/aiservice'
      })
    },
    
    // 跳转到商品详情
    goToProductDetail(productId) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${productId}`
      })
    }
  }
}
</script>

<style>
page {
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.search-container {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #ffffff;
  flex-shrink: 0;
}

.search-box {
  flex: 1;
  height: 64rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
}

.search-icon {
  width: 20px;
  height: 20px;
  margin-right: 8rpx;
}

.search-placeholder {
  font-size: 28rpx;
  color: #999999;
}

.header-icons {
  display: flex;
  align-items: center;
  margin-left: 24rpx;
}

.ai-service-icon, .message-icon, .cart-icon {
  width: 24px;
  height: 24px;
  margin-left: 24rpx;
}

.content {
  flex: 1;
  overflow: auto;
}

.banner {
  width: 750rpx;
  height: 422rpx;
  margin-bottom: 20rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.nav-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 24rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.nav-item {
  width: 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20rpx;
}

.nav-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 8rpx;
}

.nav-text {
  font-size: 24rpx;
  color: #666666;
}

.product-section {
  background-color: #ffffff;
  padding: 24rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.more-link {
  display: flex;
  align-items: center;
}

.more-text {
  font-size: 24rpx;
  color: #999999;
  margin-right: 4rpx;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.product-card {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #ffffff;
  border-radius: 8rpx;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 345rpx;
}

.product-info {
  padding: 16rpx;
}

.product-tag {
  display: inline-block;
  font-size: 20rpx;
  color: #ff0036;
  padding: 4rpx 8rpx;
  border: 1px solid #ff0036;
  border-radius: 4rpx;
  margin-bottom: 8rpx;
}

.product-title {
  font-size: 28rpx;
  color: #333333;
  line-height: 36rpx;
  height: 72rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 8rpx;
}

.product-price-box {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.price-symbol {
  font-size: 24rpx;
  color: #ff5000;
}

.product-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff5000;
  margin-right: 8rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999999;
  text-decoration: line-through;
}

.sales-count {
  font-size: 24rpx;
  color: #999999;
}
</style>

